<?php
namespace app\Controller;

use lib\View;
use app\Model\Album;

class ImageController
{
	public function edit()
	{
		$gid = $this->input('g');
		$id = $this->input('m');

		$album = Album::find(['id' => $gid]);
		$image = null;

		foreach ($album->imageCollection as $img) {
			if ($img->id == $id) {
				$image = $img;
				break;
			}
		}
		return new View('image/edit', ['image' => $image, 'album' => $album]);
	}

	public function update()
	{
		$gid = $this->input('g');
		$id = $this->input('m');
		$title =  $this->input('title');
		$description =  $this->input('description');

		$album = Album::find(['id' => $gid]);

		for ($i=0; $i<count($album->imageCollection); $i++) {
			if ($album->imageCollection[$i]->id === $id) {
				$album->imageCollection[$i]->title = $title;
				$album->imageCollection[$i]->description = $description;
				break;
			}
		}
		$album->save();
		header('Location:' . url('album/detail', ['id' => $gid]));
	}

	public function delete()
	{
		$gid = $this->input('g');
		$id = $this->input('m');

		$album = Album::find(['id' => $gid]);
		$new = $album->toArray();
		
		for ($i=0; $i<count($new['imageCollection']); $i++) {
			if ($new['imageCollection'][$i]['id'] === $id) {
				//删除图片实体
				unlink(PUBLIC_DIR . DIRECTORY_SEPARATOR .$new['imageCollection'][$i]['path']);
				//删除图片在相册中的显示
				unset($new['imageCollection'][$i]);
				break;
			}
		}
		$album = Album::fromArray($new);
		$album->cover();
		$album->save();
		header('Location:' . url('album/detail', ['id' => $gid]));

	}

	public function add()
	{
		$gid = $this->input('g');
		return new View('image/add', ['gid' => $gid]);
	}

	public function upload()
	{
		$gid = $this->input('g');
		$album = Album::find(['id' => $gid]);

		$album->upload();
		$album->save();

		header('Location:' . url('album/detail', ['id' => $gid]));
	}

	private function input($name)
    {
       	return htmlspecialchars(stripslashes($_REQUEST[$name]));
    }
}